#-*- coding: UTF-8 -*-
import MySQLdb
import MySQLdb.cursors
import datetime
import sys
reload(sys)
sys.setdefaultencoding('utf-8')

conn= MySQLdb.connect(
        host='127.0.0.1',
        port = 3306,
        user='root',
        passwd='01827746521',
        db ='fof',
        cursorclass = MySQLdb.cursors.DictCursor,
        charset="utf8"
        )
cur = conn.cursor()

def getMinDateByFid(fid):
    sql = "select min(statistic_date) as statistic_date from fund_nav where fund_id = %d" % fid
    cur.execute(sql)
    return cur.fetchone()['statistic_date']

def getMaxDateByFid(fid):
    sql = "select max(statistic_date) as statistic_date from fund_nav where fund_id = %d" % fid
    cur.execute(sql)
    return cur.fetchone()['statistic_date']

def completeFundItemIndicator(fid):
    minDate = getMinDateByFid(fid)
    maxDate = getMaxDateByFid(fid)

    while minDate < maxDate:
        sql = "select fund_id from fund_nav where fund_id = %d and statistic_date = '%s'" % (fid,minDate)
        cur.execute(sql)
        if not cur.fetchone():
            selectSql = "select * from fund_nav where fund_id = %d and statistic_date = '%s'" % (fid,minDate + datetime.timedelta(-1))
            cur.execute(selectSql)
            yesterdayRow = cur.fetchone();
            print "# ",fid,minDate.strftime('%Y-%m-%d %H:%M:%S')
            insertSql = "INSERT INTO fund_nav (fund_id,fund_ext_code,fund_ext_source,fund_name,nav,added_nav,swanav,pc,cpc,statistic_date) VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s');" % (yesterdayRow['fund_id'],yesterdayRow['fund_ext_code'],yesterdayRow['fund_ext_source'],yesterdayRow['fund_name'],yesterdayRow['nav'],yesterdayRow['added_nav'],yesterdayRow['swanav'],yesterdayRow['pc'],yesterdayRow['cpc'],minDate.strftime('%Y-%m-%d %H:%M:%S'))
            ret = cur.execute(insertSql)
            print insertSql

        minDate = minDate + datetime.timedelta(+1)



cur.execute("select DISTINCT(fund_id) as fId from fund_nav")
allRows = cur.fetchall();


for row in allRows:
    fid = row['fId']
    completeFundItemIndicator(fid)
